var zt;
var noc_id = 0;
var now_call_uid =0;
$.cookie('header','header-fixed', { expires: 1});

$(function () {
    //BEGIN MENU SIDEBAR
    $('#sidebar').css('min-height', '100%');
    $('#side-menu').metisMenu();
    $(window).on("load resize", function () {
        if ($(this).width() < 768) {
            $('body').removeClass();
            $('div.sidebar-collapse').addClass('collapse');
        } else {
            $('body').addClass($.cookie('menu_style') + ' ' + $.cookie('header'));
            $('div.sidebar-collapse').removeClass('collapse');
            $('div.sidebar-collapse').css('height', 'auto');
        }

        if($('#sidebar').height() > $('#page-wrapper').height()){
			
            //$('#wrapper').css('height', $('#sidebar').height());
        }
    });

    $('#news-ticker-close').click(function(e){
        $('.news-ticker').remove();
        $('.quick-sidebar').css('top', '50px');
    });
    //END NEWS TICKER TOPBAR

    //BEGIN TOPBAR DROPDOWN
    $('.dropdown-slimscroll').slimScroll({
        "height": '250px',
        "wheelStep": 30
    });
    //END TOPBAR DROPDOWN

    //BEGIN CHECKBOX & RADIO
    if($('#demo-checkbox-radio').length <= 0){
        $('input[type="checkbox"]:not(".switch")').iCheck({
            checkboxClass: 'icheckbox_minimal-grey',
            increaseArea: '20%' // optional
        });
        $('input[type="radio"]:not(".switch")').iCheck({
            radioClass: 'iradio_minimal-grey',
            increaseArea: '20%' // optional
        });
    }
    //END CHECKBOX & RADIO

    //BEGIN TOOTLIP
    $("[data-toggle='tooltip'], [data-hover='tooltip']").tooltip();
    //END TOOLTIP

    //BEGIN POPOVER
    $("[data-toggle='popover'], [data-hover='popover']").popover();
    //END POPOVER
    
    //BEGIN THEME SETTING
    $('#theme-setting > a.btn-theme-setting').click(function(){
        if($('#theme-setting').css('right') < '0'){
            $('#theme-setting').css('right', '0');
        } else {
            $('#theme-setting').css('right', '-250px');
        }
    });

    // Begin Change Theme Color
    var list_menu = $('.dropdown-theme-setting > li > select#list-menu');
    var list_style = $('.dropdown-theme-setting > li > select#list-style');
    var list_header = $('.dropdown-theme-setting > li > select#list-header');
    var list_color = $('.dropdown-theme-setting > li > ul#list-color > li');

    // FUNCTION CHANGE URL STYLE ON HEAD TAG
    var setTheme = function (menu_style, style, header, color) {
        $.cookie('menu_style', menu_style);
        $.cookie('style',style);
        $.cookie('header',header);
        $.cookie('color',color);	 
        $('body').removeClass();
        $('body').addClass(menu_style + ' ' + header);
        // Set slimscroll when sidebar fixed
        if ($('body').hasClass('sidebar-collapsed')) {
            // Use for menu style 1 & 2
           $('#side-menu').attr('style','').parent('.slimScrollDiv').replaceWith($('#side-menu'));
        } else {
            // Use for menu style 4
            setTimeout(function(){
                $('#side-menu').slimScroll({
                    "height": $(window).height() - 50,
                    'width': '250px',
                    "wheelStep": 5
                });
                $('#side-menu').focus();
            }, 50)
        }
        $('#theme-change').attr('href', _public_path+'/css/themes/'+ style + '/' + color + '.css');
		//alert(_public_path+'/css/themes/'+ style + '/' + color + '.css');
    }
	
 
    // INITIALIZE THEME FROM COOKIE
    // --NOTES: HAVE TO SET VALUE FOR STYLE & COLOR BEFORE AND AFTER ACTIVE THEME
    // Check cookie when window reload and set value for each option(menu,style,color)
    //setTheme($.cookie('menu_style'), $.cookie('style'),'header-fixed', $.cookie('color'));
    if ($.cookie('style')) {
		//alert(111);
        // FIX SIDEBAR IN HORIZONTAL AND RIGHT
        if ($('body').hasClass('clear-cookie')) {
            $.removeCookie('menu_style');
		
        } else {
             
            list_menu.find('option').each(function(){
                if($(this).attr('value') == $.cookie('menu_style')) {
                    $(this).attr('selected', 'selected');
                }
            });
            
            list_style.find('option').each(function(){
                if($(this).attr('value') == $.cookie('style')) {
                    $(this).attr('selected', 'selected');
                }
            });

          /*  list_header.find('option').each(function(){
                if($(this).attr('value') == $.cookie('header')) {
                    $(this).attr('selected', 'selected');
                }
            });*/

            list_color.removeClass("active");
            list_color.each(function(){

                if($(this).attr('data-color') == $.cookie('color')){
                    $(this).addClass('active');
                }
            });
		
            setTheme($.cookie('menu_style'), $.cookie('style'),'header-fixed', $.cookie('color'));
        }
		
    };

    //读取用户操作展开/收缩状态
	if($.cookie('mtoggle')){
		var a=$.cookie('mtoggle');
		//alert(a);	
		if(a=='shrank'){	
			$('body').addClass('sidebar-collapsed');	
            $('#menu-toggle').trigger('click');//绑定默认单击事件，用户进入页面默认单击一次jquery中的API中有详解			 
		}else if(a=='deploy'){
		    $('body').removeClass('sidebar-collapsed');
		}			
	}
	//结束
	

    // SELECT MENU STYLE EVENT
    list_menu.on('change', function(){
        list_color.each(function() {
            if($(this).hasClass('active')){
                color_active  = $(this).attr('data-color');
            }
        });
        // No Menu style 3 fixed
        if (($.cookie('header') == 'header-fixed') && ($(this).val() == 'sidebar-icons')) {
            setTheme($(this).val(), list_style.val(), 'header-fixed', color_active);
            return;
        }
        setTheme($(this).val(), list_style.val(), 'header-fixed', color_active);
    });
    // SELECT STYLE EVENT
    list_style.on('change', function() {
        list_color.each(function() {
            if($(this).hasClass('active')){
                color_active  = $(this).attr('data-color');
            }
        });
        setTheme(list_menu.val(), $(this).val(), 'header-fixed', color_active);
    });

    // SELECT HEADER EVENT
    list_header.on('change', function() {
        list_color.each(function() {
            if($(this).hasClass('active')){
                color_active  = $(this).attr('data-color');
            }
        });
        // No Menu style 3 fixed
        if (($.cookie('menu_style') == 'sidebar-icons') && ($(this).val() == 'header-fixed')) {
            return;
        }
        setTheme(list_menu.val(), list_style.val(), 'header-fixed', color_active);
    });
    // LI CLICK EVENT
       list_color.on('click', function() {
        list_color.removeClass('active');
        $(this).addClass('active');
        setTheme(list_menu.val(), list_style.val(), 'header-fixed', $(this).attr('data-color'));
        //传data-color到userAction
         var url= 'index.php?m=user&a=userColor&t=' + Math.random(1000)+'&color='+ $(this).attr('data-color');        
         //console.log(url);
          $.get(url, function(data){}) ;
    });
    $('.btn-fullscreen').click(function() {

        if (!document.fullscreenElement &&    // alternative standard method
            !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement ) {  // current working methods
            if (document.documentElement.requestFullscreen) {
                document.documentElement.requestFullscreen();
            } else if (document.documentElement.msRequestFullscreen) {
                document.documentElement.msRequestFullscreen();
            } else if (document.documentElement.mozRequestFullScreen) {
                document.documentElement.mozRequestFullScreen();
            } else if (document.documentElement.webkitRequestFullscreen) {
                document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
            }
        } else {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen();
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            }
        }
    });
    //END FULL SCREEN

    // BEGIN FORM CHAT
    $('.btn-chat').click(function () {
        if($('#chat-box').is(':visible')){
            $('#chat-form').toggle('slide', {
                direction: 'right'
            }, 500);
            $('#chat-form').slimScroll();
            $('#chat-box').hide();
        } else{
            $('#chat-form').toggle('slide', {
                direction: 'right'
            }, 500);
            $('#chat-form > .chat-inner').slimScroll({
                "height": $(window).height(),
                'width': '280px',
                "wheelStep": 30
            });
        }
    });
    $('.chat-box-close').click(function(){
        $('#chat-box').hide();
        $('#chat-form .chat-group a').removeClass('active');
    });
    $('.chat-form-close').click(function(){
        $('#chat-form').toggle('slide', {
            direction: 'right'
        }, 500);
        $('#chat-box').hide();
    });

    init_InfoPanel();
        //点击page-content其它区域，面板收回
 
 


    $('#chat-form .chat-group a').unbind('*').click(function(){
        $('#chat-box').hide();
        $('#chat-form .chat-group a').removeClass('active');
        $(this).addClass('active');
        var strUserName = $('> small', this).text();
        $('.display-name', '#chat-box').html(strUserName);
        var userStatus = $(this).find('span.user-status').attr('class');
        $('#chat-box > .chat-box-header > span.user-status').removeClass().addClass(userStatus);
        var chatBoxStatus = $('span.user-status', '#chat-box');
        var chatBoxStatusShow = $('#chat-box > .chat-box-header > small');
        if(chatBoxStatus.hasClass('is-online')){
            chatBoxStatusShow.html('在线');
        } else if(chatBoxStatus.hasClass('is-offline')){
            chatBoxStatusShow.html('离线');
        } else if(chatBoxStatus.hasClass('is-busy')){
            chatBoxStatusShow.html('忙');
        } else if(chatBoxStatus.hasClass('is-idle')){
            chatBoxStatusShow.html('空闲');
        }

        var offset = $(this).offset();
        var h_main = $('#chat-form').height();
        var h_title = $("#chat-box > .chat-box-header").height();
        var top = ($('#chat-box').is(':visible') ? (offset.top - h_title - 40) : (offset.top + h_title - 20));

        if((top + $('#chat-box').height()) > h_main){
            top = h_main - 	$('#chat-box').height();
        }

        $('#chat-box').css({'top': top});

        if(!$('#chat-box').is(':visible')){
            $('#chat-box').toggle('slide',{
                direction: 'right'
            }, 500);
        }
        // FOCUS INPUT TEXT WHEN CLICK
        $("#chat-box .chat-textarea input").focus();
        $('.chat-content > .chat-box-body').slimScroll({
            "height": "250px",
            'width': '340px',
            "wheelStep": 30,
            "scrollTo": $(this).height() 
        });
    });
    // Add content to form
    $('.chat-textarea input').on("keypress", function(e){
        var $obj = $(this);
        var $me = $obj.parent().parent().find('ul.chat-box-body');
        var $my_avt = '#';
        var $your_avt = '#';
        if (e.which == 13) {
            var $content = $obj.val();

            if ($content !== "") {
                var d = new Date();
                var h = d.getHours();
                var m = d.getMinutes();
                if (m < 10) m = "0" + m;
                $obj.val(""); // CLEAR TEXT ON TEXTAREA

                var $element = ""; 
                $element += "<li>";
                $element += "<p>";
                $element += "<img class='avt' src='"+$my_avt+"'>";
                $element += "<span class='user'>管理员</span>";
                $element += "<span class='time'>" + h + ":" + m + "</span>";
                $element += "</p>";
                $element = $element + "<p>" + $content +  "</p>";
                $element += "</li>";
                
                $me.append($element);
                var height = 0;
                $me.find('li').each(function(i, value){
                    height += parseInt($(this).height());
                });

                height += '';
                $me.scrollTop(height);  

                // RANDOM RESPOND CHAT
                var $res = "";
                $res += "<li class='odd'>";
                $res += "<p>";
                $res += "<img class='avt' src='"+$your_avt+"'>";
                $res += "<span class='user'>钱冬君</span>";
                $res += "<span class='time'>" + h + ":" + m + "</span>";
                $res += "</p>";
                $res = $res + "<p>" + "Ok 我知道了" + "</p>";
                $res += "</li>";
                setTimeout(function(){
                    $me.append($res);
                    $me.scrollTop(height+100);        
                }, 1000);
            }
        }
    });
    //END FORM CHAT

    //BEGIN PORTLET
    $(".portlet").each(function(index, element) {
        var me = $(this);
        $(">.portlet-header>.tools>i", me).click(function(e){
            if($(this).hasClass('fa-chevron-up')){
                $(">.portlet-body", me).slideUp('fast');
                $(this).removeClass('fa-chevron-up').addClass('fa-chevron-down');
            }
            else if($(this).hasClass('fa-chevron-down')){
                $(">.portlet-body", me).slideDown('fast');
                $(this).removeClass('fa-chevron-down').addClass('fa-chevron-up');
            }
            else if($(this).hasClass('fa-cog')){
                //Show modal
            }
            else if($(this).hasClass('fa-refresh')){
                //$(">.portlet-body", me).hide();
                $(">.portlet-body", me).addClass('wait');

                setTimeout(function(){
                    //$(">.portlet-body>div", me).show();
                    $(">.portlet-body", me).removeClass('wait');
                }, 1000);
            }
            else if($(this).hasClass('fa-times')){
                me.remove();
            }
        });
    });
    //END PORTLET

    //BEGIN BACK TO TOP
    $(window).scroll(function(){
        if ($(this).scrollTop() < 200) {
            $('#totop') .fadeOut();
        } else {
            $('#totop') .fadeIn();
        }
    });
    $('#totop').on('click', function(){
        $('html, body').animate({scrollTop:0}, 'fast');
        return false;
    });
    //END BACK TO TOP

    //BEGIN CHECKBOX TABLE
    $('.checkall').on('ifChecked ifUnchecked', function(event) {
        if (event.type == 'ifChecked') {
            $(this).closest('table').find('input[type=checkbox]').iCheck('check');
        } else {
            $(this).closest('table').find('input[type=checkbox]').iCheck('uncheck');
        }
    });
        //ONLY FOR USER_PROFILE PAGE
    $('.checkall-email').on('ifChecked ifUnchecked', function(event) {
        if (event.type == 'ifChecked') {
            $(this).closest('.tab-pane').find('input[type=checkbox]').iCheck('check');
        } else {
            $(this).closest('.tab-pane').find('input[type=checkbox]').iCheck('uncheck');
        }
    });
    //END CHECKBOX TABLE

    $('.option-demo').hover(function() {
        $(this).append("<div class='demo-layout animated fadeInUp'><i class='fa fa-magic mrs'></i>Demo</div>");
    }, function() {
        $('.demo-layout').remove();
    });
      $('#header-topbar-page .demo-layout').live('click', function() {
        var HtmlOption = $(this).parent().detach();
        $('#header-topbar-option-demo').html(HtmlOption).addClass('animated flash').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
            $(this).removeClass('animated flash');
        });
        $('#header-topbar-option-demo').find('.demo-layout').remove();
        return false;
    });
    $('#title-breadcrumb-page .demo-layout').live('click', function() {
        var HtmlOption = $(this).parent().html();
        $('#title-breadcrumb-option-demo').html(HtmlOption).addClass('animated flash').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
            $(this).removeClass('animated flash');
        });
        $('#title-breadcrumb-option-demo').find('.demo-layout').remove();
        return false;
    });
    // CALL FUNCTION RESPONSIVE TABS
    fakewaffle.responsiveTabs(['xs', 'sm']);

    // BEGIN SEARCH FORM ON TOPBAR
    $('#topbar-search').on('click', function (e) {
       /*  $(this).addClass('open');
         $(this).find('.form-control').focus();

         $('#topbar-search .form-control').on('blur', function (e) {
             $(this).closest('#topbar-search').removeClass('open');
            $(this).unbind('blur');
         });*/
    });
    // END SEARCH FORM ON TOPBAR

    // BEGIN DATERANGE PICKER ON BREADCRUMB
    $('.reportrange').daterangepicker(
        {
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1)],
                'Last 7 Days': [moment().subtract('days', 6), moment()],
                'Last 30 Days': [moment().subtract('days', 29), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')]
            },
            startDate: moment().subtract('days', 29),
            endDate: moment(),
            opens: 'left',
        },
        function(start, end) {
            $('.reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
            $('input[name="datestart"]').val(start.format("YYYY-MM-DD"));
            $('input[name="endstart"]').val(end.format("YYYY-MM-DD"));
        }
    );
    $('.reportrange span').html(moment().subtract('days', 29).format('MMMM D, YYYY') + ' - ' + moment().format('MMMM D, YYYY'));
    //END PLUGINS DATE RANGE PICKER
    keep_online();


	
});

//弹屏号码数组
var phoneslist = new Array();
function keep_online()
{     
   var last_time_pickup = 0;
    
    var iframe = window.frames['switch-state'];   
    if( typeof(iframe) == "undefined"){
        var work_mode = 0;
       
    }else{
        
        var work_mode = 0;
        typeState = checkDesktopStatus();
         if(typeState){
            work_mode = 1;
            
         }else{
            
            work_mode = 2;
         }
          last_time_pickup = iframe.last_time_pickup;
        }
  /*  jQuery.ajax({
      type: 'GET',
      url: 'index.php?m=User&a=keepOnline',
     dataType: "json",
     data: {'work_mode':work_mode,'t': Math.random()},
      success: function(data){
        if(data.error){         
            alert(data.msg);
            window.location="index.php?m=user&a=logout";
        }else{
           
           //给分机状态赋值
           if(_my_exten){
               if(data.exten_state_text != '' && $('#exten_state_text') !=null){
                    $('#exten_state_text').html(data.exten_state_text + data.tips);
                    $("#exten_state_fa").attr('class',data.exten_state+' '+data.icon);
                    $("#exten_state_fa").attr('title',data.tips);

                    //$('#toggle-state-switch').bootstrapSwitch('setState', false); 
                    if(data.exten_state =="busy" || data.exten_state =="dnd"){
                        $('#btn-dnd').bootstrapSwitch('setState', true); 
                    }else{
                         $('#btn-dnd').bootstrapSwitch('setState', false); 
                    }
                }      
            }

            //触发弹屏
            if(data.call_uid != now_call_uid){
                now_call_uid = data.call_uid;
                //$("#div_phone_list").innerHTML =data.content.call_phone;
                var newphone = new Array(data.call_uid,
                                        data.call_phone,
                                        data.call_time,
                                        data.call_cid,
                                        data.call_did,
                                        data.call_queue_id,
                                        data.call_type,
                                        data.call_type_text,
                                        data.call_type_icon);
                  phoneslist.unshift(newphone);
             
                  phoneslist.length = 10;//留下10条记录
                  var s = "";
                    for(var i=0;i<phoneslist.length;i++){
                        if(typeof(phoneslist[i]) != "undefined"){
                            if(phoneslist[i][6] == "1"){
                                var label = "label-success";
                            }else{
                                var label = "label-info";
                            }
                            s += '<li><a href=\'javascript:popPhoneBox("'+phoneslist[i][0]+'","'+phoneslist[i][1]+'","'+phoneslist[i][2]+'","'+phoneslist[i][3]+'","'+phoneslist[i][4]+'","'+phoneslist[i][5]+'","'+phoneslist[i][6]+'","'+phoneslist[i][7]+'","'+phoneslist[i][8]+'")\'><span class="label '+ label +'"><i class="fa '+phoneslist[i][8]+'"></i></span>'+phoneslist[i][1]+'<span class="pull-right text-muted small">'+phoneslist[i][2]+'</span></a></li>';
                        }
                    }
                    
                    $("#div_phone_list").html("<ul>"+s+"</ul>");
                    popPhoneBox(data.call_uid,data.call_phone,data.call_time,data.call_cid,data.call_did,data.call_queue_id,data.call_type,data.call_type_text,data.call_type_icon);
            } 
             
           //如果有消息
           if(data.have_noc> 0){
       
              if(noc_id != data.have_noc){
                 //sms_now_time = now_time;
                 noc_id = data.have_noc;
                 //console.log(noc_id);
                 noc_mon();
              }
           }else{
            nbsp='';
            noc_id =0;
            jQuery("#message_count").html(nbsp);
           }
       
        }

      },
     error: function (request, textStatus, errorThrown){
    
     }
   }); */
   //window.setTimeout(online_mon,monInterval.exten_state*1000);
   setTimeout(keep_online,1000);
}

//¼ÓÔØ±íµ¥ÑéÖ¤
function init_form(){
    $(".form-validate").validate({
        errorPlacement: function(error, element)
        {
            error.insertAfter(element);
        }
    });
    $(".form-validate-signin").validate({
        errorPlacement: function(error, element)
        {
            error.insertAfter(element);
        }
    });
    $(".form-validate-signup").validate({
        rules: {
            age: {
                range: [0,100]
            }
        },
        errorPlacement: function(error, element)
        {
            error.insertAfter(element);
        }
    });
}


function modalUrl(url){  
	//alert(url);
	url += '&t=' + Math.random(1000)  
	$.get(url, '', function(data){  
		$('#mymodal').html(data)  ;
		init_form();
	})
	$('#mymodal').modal({show:true});
}


// 展开隐藏信息面板 zhangtuo 2015-11-3
function showPanel(url){ 

     //隐藏掉滚动条，并设置宽度
    $("body").eq(0).width($("body").eq(0).width());
    $("body").eq(0).css("overflow","hidden");
    //定位面板的位置
    //alert("展开面板");

    $.get(url+'&t=' + Math.random(1000), function(data){
     //alert("Data Loaded: " + data);
      $("#info-panel .panel-inner").html(data);
        $('#info-panel .panel-inner').slimScroll({
            height: $(window).height() - 50,
            width: '950px',
            alwaysVisible: true,
            wheelStep: 100
        });

    $('#info-panel').css('margin-top',$(document).scrollTop());
    $('#info-panel').css('right','-950px');
    $('#info-panel').css('height',$(window).height() - 50);

   $('#info-panel').show();
   $('#info-panel').animate({right:'0px'});


   });

};



//添加任务日程
// url_param string 类型，必须项r=RCustomerTask&module=customer&id={$customer.customer_id}
function add_task(url_param){
     $.get('index.php?m=todo&a=add&t='+Math.random(1000),url_param, function(data){
        parent.layer.open({
            type: 1,
            area: ['530px', '400px'],
            title: '添加任务',
            shadeClose:true,
            content: data
        });
    }) 
}
function edit_task(url_param){
     $.get('index.php?m=todo&a=edit&t='+Math.random(1000),url_param, function(data){
        parent.layer.open({
            type: 1,
            area: ['530px', '400px'],
            title: '编辑任务',
            shadeClose:true,
            content: data
        });
    }) 
}


function init_InfoPanel(){
    $(".page-content").bind("click",function(e){ 

    var target = $(e.target);
    //console.log(target); 
    if(target.closest(".like").length == 0){

    $('#info-panel').animate({right:'-950px'});
    $('#info-panel').hide();
        
        //$('#info-panel').animate({right:'0px',width:'hide'},1000);
        $("body").eq(0).css("overflow-y",'auto');
        $("#info-panel .panel-inner").html("");
    };


        
        //$('#info-panel').hide();
    });

    
}



//请求一个url，返回结果并显示，可以设置是否弹出确问询
function ajax_do(url,param,show_confirm ,confirm_title,confirm_text){
  if(show_confirm){
    swal({
        title: confirm_title,
        text: confirm_text,
        type: "info",
        confirmButtonText:'确定',
        cancelButtonText:'取消',
        showCancelButton: true,
        closeOnConfirm: false,
        showLoaderOnConfirm: true, 
      }, 
      function(){
        $.post(url+'&t=' + Math.random(1000),param, function(data){
          swal.close();
          parent.layer.open({
            type: 1,
            title: false,
            closeBtn: false,
            shadeClose:true, //点击遮罩层 关闭
            content: data,
            end: function(index){
             
            }
          });
          
        }, 'html');
      
      });
  }else{
    $.post(url+'&t=' + Math.random(1000),param, function(data){
      parent.layer.open({
        type: 1,
        title: false,
        closeBtn: false,
        shadeClose:true, //点击遮罩层 关闭
        content: data,
        end: function(index){
          //parent.layer.closeAll();
        
        }
      });
      
    }, 'html');

  }

}

//绘画出柱状图
function getChangeXml(val,chart_name,swf){
	if(typeof(swf) == 'undefined'){
		swf = "column3d.swf"
	}
	var so = new FusionCharts(_public_path+"/images/charts/"+swf, "ChartId", "1000", "400");
	so.addParam("wmode", "transparent");
	so.setDataXML(val);		   
	so.render(chart_name);
}

var nowPageUrl = "";
var nowPageTitle = "";
var nowPageTarget = "";
function loadPage(pageTitle,url,target){

    $('#info-panel').animate({right:'-950px'});
    $('#info-panel').hide();

    nowPageTitle =pageTitle;
   nowPageUrl =url;
   nowPageTarget =target;
    if(target=="_blank"){
        window.open(url);
    }else{
        $("#page_title").html(pageTitle);
        if(target == 0 || target==""){
            $("#nanyou-page-content").load(url+'&nanyou_hide_footer=1&nanyou_hide_header=1&t=' + Math.random(1000));        
        }else{
            $("#"+target).load(url+'&nanyou_hide_footer=1&nanyou_hide_header=1&t=' + Math.random(1000));        
        }
    }
}

function reloadPage(){
    loadPage(nowPageTitle,nowPageUrl,nowPageTarget);
}
//读取返回的json字符串，生成最新消息列表
function getThreeMessages(){
    //消息个数
            // var a = 2;
            // alert($('#message_count').innerText);
            // $('#message_count').innerText = a;
    var date = new Date();
    $.ajax({
        url: 'index.php?m=Message&a=getMes',
        success: function(data){
        notesJson=eval(data);
        if(data == notesJsonCopy)
            return;
       
        //消息id
        $idArray = $('.message_id');
        //消息内容
        $noteArray = $('.note');
        //消息发送时间
        $smallArray = $('.small');
       // alert($message_count.innerText);
        for (var i = 0; i<data.length; i++) {
            $("#mes").append("<li><a class='message_id'><span class='label label-blue'><i class='fa fa-comment'></i></span><span class='note'></span><span class='pull-right text-muted small'></span></a></li>");
            $noteArray[i].innerText = notesJson[i]['note'];
            $smallArray[i].innerText = notesJson[i]['send_time'];
            var id = notesJson[i]['message_id'];
            $idArray[i].href = "javascript:view_message("+id+");"
            }
            
        }  
        
    });
    notesJsonCopy=notesJson;



}

toastr.options = {
  "closeButton": false,
  "debug": false,
  "positionClass": "toast-bottom-right",
  "showDuration": "300",
  "hideDuration": "1000",
  "timeOut": "10000000000",
  "extendedTimeOut": "500000000",
  "showEasing": "swing",
  "hideEasing": "linear",
  "showMethod": "fadeIn",
  "hideMethod": "fadeOut"
}

//检测坐席签入状态
//如果是未签入，返回0，即没有打开签入页面
//如果是就绪，返回1  
//如果是示忙,返回2
function checkDesktopStatus(){
    if($('#switch-state').attr('checked')){
        return true;
    }else{
        return false;
    }
}




function popPhoneBox(call_uid,call_phone,call_time,call_cid,call_did,call_queue_id,call_type,call_type_text,call_type_icon){

    $.getJSON('index.php?m=customer&a=getCustomerIDByPhoneNum&phone_num='+call_phone+'&t=' + Math.random(1000), '', function(data){ 
    if(data.customer_id != 0){
        var url ='index.php?m=customer&a=view&id='+data.customer_id; 
    }else{
        var url ='index.php?m=customer&a=add&phone_num='+call_phone;        
    }


layer.open({
  type: 1,
  title: false,
  closeBtn: 0, //不显示关闭按钮
  shade: [0],//透明度0 ，全透明

  area: ['340px', '215px'],
  offset: 'rb', //右下角弹出
  time: 600, //2秒后自动关闭
  shift: 1,
  content: '<div>'+call_type_text +" : "+call_phone+'</div>', //iframe的url，no代表不显示滚动条
  end: function(){ //此处用于演示
   $.get(url+'&t=' + Math.random(1000), '', function(data){  
        var h = $(window).height();
        var w = $(window).width();
        layer.open({
          type: 1,
          title:  call_phone +"　　"+call_type_text ,
           closeBtn: true, //不显示关闭按钮
          shadeClose: true,
          offset: [ //为了演示，随机坐标
                Math.random()*(100)
                ,Math.random()*($(window).width()-950)
          ],          
          shade: false,
          scrollbar: true,
          maxmin: true, //开启最大化最小化按钮
          area: ['950px', (h-100)+'px'],
          content: data,
        });
    });
  }
});



});




}


//点击拨号方法
//phone 拨打哪个号码
//附件参数，默认为空 
//主叫名字，默认为空
//zhangtuo  2016-5-13 
function dial(phone,variable,callername)
{
    var url = 'index.php?m=api&a=clickCall&phone='+phone+'&variable='+variable+'&callername='+callername+'&'+ Math.random();
    $.getJSON(url, function(data){
    });
}

//设置免打扰
//1表示开启免打扰
//0表示关闭免打扰
function setDND(is_dnd){
    var url = 'index.php?m=api&a=setDND&is_dnd='+is_dnd+'&'+ Math.random();
    $.getJSON(url, function(data){
        if(data.error > 0 ){
            swal(data.msg, "", "warning");
        }
    });
}